import { Component, OnInit } from '@angular/core';
import {
  AbstractControl,
  AsyncValidatorFn,
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  ValidatorFn,
  Validators
} from '@angular/forms';
import { Observable, Observer } from 'rxjs';

import { NzSafeAny } from 'ng-zorro-antd/core/types';

// get post请求，还需要引入httpHeaders
import { HttpClient, HttpHeaders } from '@angular/common/http'



interface ItemData {
  id: string;
  name: string;
  age: string;
  address: string;
}

@Component({
  selector: 'app-demo-ws',
  templateUrl: './demo-ws.component.html',
  styleUrls: ['./demo-ws.component.less'],
})

export class DemoWsComponent implements OnInit {

  // 声明


  xxx01() {
    console.log('点击');

  }

  // 02
  i = 0;
  editId: string | null = null;
  listOfData: ItemData[] = [];

  value?: string;


  ngOnInit(): void {
    // 模拟初始化数据渲染
    // for (let i = 0; i < 2; i++) {
    //   this.addRow();
    // }
  }

  startEdit(id: string): void {
    this.editId = id;
  }

  stopEdit(): void {
    this.editId = null;
  }

  addRow(): void {
    console.log('add');

    // 添加行数-模拟数据
    // this.listOfData = [
    //   ...this.listOfData,
    //   {
    //     id: `${this.i}`,
    //     name: `Edward King ${this.i}`,
    //     age: '32',
    //     address: `London, Park Lane no. ${this.i}`
    //   }
    // ];
    // this.i++;
  }

  deleteRow(id: string): void {
    this.listOfData = this.listOfData.filter(d => d.id !== id);
  }


  // 弹窗============================
  isVisible = false;
  isOkLoading = false;

  showModal(): void {
    this.isVisible = true;
  }

  handleOk(): void {
    this.isOkLoading = true;
    setTimeout(() => {
      this.isVisible = false;
      this.isOkLoading = false;
    }, 3000);
  }

  handleCancel(): void {
    this.isVisible = false;
  }

  // 定义表单数据======================
  validateForm: FormGroup<{
    name: FormControl<string>;
    sex: FormControl<string>;
    age: FormControl<string>;
    departmentId: FormControl<string>;
    jcbw: FormControl<string>;
    ultrasoundNumber: FormControl<string>;
    cfz: FormControl<string>;
    datePickerTime: FormControl<Date | null>;
  }>
  //  = this.fb.group({
  //   datePickerTime: this.fb.control<Date | null>(null),
  // });
  // 配置表单内容以及校验===============
  constructor(private fb: NonNullableFormBuilder, public http: HttpClient) {
    // use `MyValidators`
    // const { required, maxLength, minLength } = MyValidators;
    this.validateForm = this.fb.group({
      // name: ['', [required, maxLength(12), minLength(6)], [this.userNameAsyncValidator]],
      name: ['', [Validators.required]],
      // name: [''],
      sex: [''],
      age: [''],
      departmentId: [''],
      jcbw: [''],
      ultrasoundNumber: [''],
      cfz: [''],
      datePickerTime: this.fb.control<Date | null>(null)
    });

    // get请求    
    // let api: any = "https://test.dingsing-medical.com/api/file/upload"; // 这里是你请求的接口
    // this.http.get(api).subscribe((response: any) => {
    //   console.log(response, 'response');
    // })

    // 首先定义请求类型【固定写法】
    // const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };

    // 定义你的api
    // var api = 'http://127.0.0.1:3000/dologin';

    // 第一个参数请求地址，第二个参数传输的数据，第三个参数就是定义的请求类型
    // this.http.post(api, { "name": "张三", "age": 20 }, httpOptions).subscribe((response) => {
    //   console.log(response);
    // });
  }

  // current locale is key of the nzAutoTips
  // if it is not found, it will be searched again with `default`
  autoTips: Record<string, Record<string, string>> = {
    'zh-cn': {
      required: '必填项'
    },
    en: {
      required: 'Input is required'
    },
    default: {
      email: '邮箱格式不正确/The input is not valid email'
    }
  };

  // 提交
  submitForm(): void {
    console.log(this.validateForm, 'this.validateForm');
    console.log(this.validateForm.valid, 'this.validateForm.valid');
    console.log(this.validateForm.value, 'this.validateForm.value');

    if (this.validateForm.valid) {
      console.log('submit', this.validateForm.value);
    } else {
      console.log('校验失败');
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }

  }

  // 重置
  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
  }

  // userNameAsyncValidator: AsyncValidatorFn = (control: AbstractControl) =>
  //   new Observable((observer: Observer<MyValidationErrors | null>) => {
  //     setTimeout(() => {
  //       if (control.value === 'JasonWood') {
  //         observer.next({
  //           duplicated: { 'zh-cn': `用户名已存在`, en: `The name is redundant!` }
  //         });
  //       } else {
  //         observer.next(null);
  //       }
  //       observer.complete();
  //     }, 1000);
  //   });









}

// current locale is key of the MyErrorsOptions
// export type MyErrorsOptions = { 'zh-cn': string; en: string } & Record<string, NzSafeAny>;
// export type MyValidationErrors = Record<string, MyErrorsOptions>;

// export class MyValidators extends Validators {
//   static override minLength(minLength: number): ValidatorFn {
//     return (control: AbstractControl): MyValidationErrors | null => {
//       if (Validators.minLength(minLength)(control) === null) {
//         return null;
//       }
//       return { minlength: { 'zh-cn': `最小长度为 ${minLength}`, en: `MinLength is ${minLength}` } };
//     };
//   }

//   static override maxLength(maxLength: number): ValidatorFn {
//     return (control: AbstractControl): MyValidationErrors | null => {
//       if (Validators.maxLength(maxLength)(control) === null) {
//         return null;
//       }
//       return { maxlength: { 'zh-cn': `最大长度为 ${maxLength}`, en: `MaxLength is ${maxLength}` } };
//     };
//   }

// }







